import moment from "moment";
const methods = {}

// 获取时间长度
methods.formatDuration = (startTime, endTime = new Date()) => {
  startTime = new Date(startTime).getTime();
  endTime = new Date(endTime).getTime();
  let ms = endTime - startTime;
  const duration = moment.duration(ms);
  let years = Math.floor(duration.asYears());
  let months = Math.floor(moment.duration(duration.asMonths() - years * 12).asMonths());
  let days = Math.floor(duration.days());
  let hours = Math.floor(duration.hours());
  let minutes = Math.floor(duration.minutes());
  let seconds = Math.floor(duration.seconds());
  let parts = [];
  if (years > 0) parts.push(years + '年');
  if (months > 0 || years > 0) parts.push(months + '月'); // 只有在有年或月的情况下才显示月
  if (days > 0 || months > 0 || years > 0) parts.push(days + '天'); // 只有在有更高单位时才显示天
  if (hours > 0 || days > 0 || months > 0 || years > 0) parts.push(hours + '时');
  if (minutes > 0 || hours > 0 || days > 0 || months > 0 || years > 0) parts.push(minutes + '分');
  if (seconds > 0 || (!years && !months && !days && !hours && !minutes)) parts.push(seconds + '秒');
  return parts.join('') || '0秒';
}


// 字符串转数组
methods.splitStr = (str = '', fh = ',') => {
  if(!str) return []
  if(!str.includes(fh)) {
    return [str]
  } else {
    return str.split(fh)
  }
}

// 获取两个数组不交集
methods.symmetricDifference = (a, b) => {
  const setA = new Set(a);
  const setB = new Set(b);
  return [...a, ...b].filter(x => !(setA.has(x) && setB.has(x)));
}

// 获取表单验证失败信息
methods.printFormError = (arr = []) => {
  let message = ''
  for(let i in arr) {
    message = arr[i][0].message
  }
  return message
}
// 深度科隆
const deepClone = (obj) => {
  // 处理基本类型和 null
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }

  // 处理数组
  if (Array.isArray(obj)) {
    return obj.map(item => deepClone(item));
  }

  // 处理对象
  const clonedObj = {};
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      clonedObj[key] = deepClone(obj[key]);
    }
  }

  // 处理函数
  if (typeof obj === 'function') {
    return obj.bind(clonedObj);
  }

  return clonedObj;
}
methods.deepClone = deepClone

methods.typeDetect = (value) => {
  if (Array.isArray(value)) {
    return "Array";
  } else if (value && typeof value === 'object') {
    return "Object";
  } else {
    return "Other Type";
  }
}


methods.toFixedTwo = (num) => {
  num = Number(num)
  if (typeof num !== 'number' || isNaN(num)) return 0.00;
  const rounded = Math.round(num * 100) / 100; // 四舍五入保留两位小数
  return rounded.toFixed(2); // 确保保留两位小数，返回 number 类型
}

methods.stringToHexColor = (str) => {
  if (!str) return '';

  // 使用djb2哈希算法
  let hash = 5381;
  for (let i = 0; i < str.length; i++) {
    hash = (hash * 33) ^ str.charCodeAt(i);
  }

  // 使用黄金分割比例来增加色相差异
  const goldenRatio = 0.61803398875;
  const hue = Math.floor((hash * goldenRatio * 360) % 360);

  // 降低亮度范围，使颜色更暗
  const saturation = ((hash % 1) + 70) + '%'; // 范围: 70% ~ 99%
  const lightness = ((hash % 15) + 35) + '%'; // 范围: 35% ~ 49% (降低并缩小范围)

  return `hsl(${hue}, ${saturation}, ${lightness})`;
}

// 获取品牌背景色
methods.getBrandBGC = (brand) => {
  if(!brand) return
  const obj = {
    '马登工装': '#767c85',
    '马登男鞋': '#feb238',
    '马登女装': '#a686f0',
    '工装': '#767c85',
    '男鞋': '#feb238',
    '女装': '#a686f0',
  }

  return obj[brand]
}

// 返回活跃排序
methods.getActiveSort = (queryParams, prop, sort) => {
  if(queryParams.number === prop && queryParams.sort === sort) {
    return '#1a9fff'
  }else {
    return ''
  }
}

// 格式化金额
methods.formatMoney = (number) => {
  if(!number) number = 0
  // 将数字乘以100，四舍五入后再除以100
  const fixedNumber = Math.round(parseFloat(number) * 100) / 100;

  // 转为字符串并分割整数和小数部分
  const parts = fixedNumber.toString().split('.');

  // 确保小数部分有两位
  if (parts.length === 1) {
    return parts[0] + '.00';
  }
  if (parts[1].length === 1) {
    return parts[0] + '.' + parts[1] + '0';
  }
  return parts[0] + '.' + parts[1];
}

// 去掉所有空格与回车
methods.removeWhitespace = (str) => {
  return str.replace(/[\s\n\r]/g, '');
}

// 转换百分比
methods.getPercentage = (val, unit = 2) => {
  let num = val || 0
  return (num * 100).toFixed(unit) + '%'
}


// 树结构转换
methods.buildTree = (data) => {
  // 首先创建一个以id为键的映射表，便于快速查找节点
  const nodeMap = {};

  // 第一步：遍历数据，创建节点映射并设置基本属性
  data.forEach(item => {
    nodeMap[item.id] = {
      ...item,
      children: []
    };
  });

  // 第二步：再次遍历，构建树结构
  const rootNodes = [];

  data.forEach(item => {
    const node = nodeMap[item.id];
    const parentId = item.parentId;

    // 如果parentId为0，表示根节点
    if (parentId === 0) {
      rootNodes.push(node);
    } else {
      // 否则，将节点添加到其父节点的children数组中
      const parentNode = nodeMap[parentId];
      if (parentNode) {
        parentNode.children.push(node);
      }
    }
  });

  // 第三步：对每个节点的子节点按orderNum排序
  function sortChildren(node) {
    if (node.children && node.children.length > 0) {
      node.children.sort((a, b) => a.orderNum - b.orderNum);
      node.children.forEach(child => sortChildren(child));
    }
  }

  rootNodes.forEach(root => sortChildren(root));

  return rootNodes;
}

methods.combineAttrValues = (attributes) => {
  // 提取所有属性的attrValues值
  const attrLists = attributes.map(attr => attr.attrValues);

  // 处理边界情况
  if (attrLists.length === 0) {
    return [];
  }

  // 使用数组的reduce方法生成所有组合
  const combinations = attrLists.reduce((acc, currentValues) => {
    if (acc.length === 0) {
      return currentValues.map(value => [value]);
    }

    const newCombinations = [];
    acc.forEach(combo => {
      currentValues.forEach(value => {
        newCombinations.push([...combo, value]);
      });
    });

    return newCombinations;
  }, []);

  // 将组合转换为字符串格式
  return combinations.map(combo => combo.join(','));
}

methods.verifyMsg = (fields = {}) => {
  for(let i in fields) {
    return fields[i][0].message
  }
}

methods.printImage = (url) => {
  if (!url) return;

  let isLoading = true;
  let hasError = false;
  let imageLoaded = false;

  // 创建一个新的图片对象来预加载图片
  const img = new Image();
  img.crossOrigin = 'anonymous'; // 处理跨域图片

  img.onload = () => {
    isLoading = false;
    imageLoaded = true;

    // 创建打印窗口
    const printWindow = window.open('', '_blank');

    // 设置打印内容
    printWindow.document.write(`
      <html>
        <head>
          <style>
            .print-image {
              width: 210mm;
              height: 140mm;
              object-fit: contain;
            }
          </style>
        </head>
        <body>
          <img src="${url}" class="print-image" alt="">
        </body>
      </html>
    `);

    printWindow.document.close();

    // 等待打印窗口加载完成后触发打印
    printWindow.onload = () => {
      setTimeout(() => {
        printWindow.print();
        // 可选：打印后关闭窗口
        // printWindow.close();
      }, 500);
    };
  };

  img.onerror = () => {

  };

  img.src = url;
}

export default methods
